import {
  Button,
  Card,
  Col,
  Form,
  Input,
  Popconfirm,
  Row,
  Space,
  Tag,
  message
} from 'antd';
import { useState } from 'react';


import commonService from '@/api/services/commonService';

export default function PickerPage() {

  const [id, setId] = useState('');
  const [info, setInfo] = useState<any>({});

  const [form] = Form.useForm();

  const handleChange = (e: any) => {
    const val = e.target.value;
    setId(val);
    getInfo(val);
  };

  const getInfo = (val?: any) => {
    commonService.getCustomApi('/admin/erp-basket/putToBasket', { orderDetailId: val || id }).then((res) => {
      setInfo(res);
      const speechMsg = new SpeechSynthesisUtterance(res.prompt);
      speechSynthesis.speak(speechMsg);
      form.resetFields();
    });
  };

  const send = (item: any) => {
    commonService.getCustomApi('/admin/order/delivery', { orderNumber: item.orderNumber }).then((res) => {
      printImage(res);
      message.success('发货完成');
      getInfo();
    });
  };

  const clearBasket = (item: any, idx: number) => {
    commonService.getCustomApi('/admin/erp-basket/clearBasket', { basketId: item.id }).then(() => {
      message.success('清理完成');
      setInfo({
        ...info, list: info.list.map((item: any, index: number) => {
          if (idx === index) {
            item.current = 0;
          }
          return item;
        })
      });
    });
  };

  const printImage = (imageUrl: string) => {
    const printWindow: any = window.open('', '_blank');
    printWindow.document.write(`<html><head><title>Print</title></head><body><img src="${imageUrl}"></body></html>`);
    printWindow.document.close();

    printWindow.onload = function () {
      printWindow.print();
      printWindow.close();
    };
  };

  return (
    <Space direction="vertical" size="large" className="w-full">
      <Card>
        <Form form={form} >

          <Row gutter={[16, 16]}>
            <Col span={8} lg={6}>
              <Form.Item<any> label="扫描条码" name="orderNumber" className="!mb-0">
                <Input autoFocus onChange={handleChange} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>

      {info.prompt ? <Card
        title='智能分拣'
      >
        <div className='flex flex-col gap-[10px]'>
          <div>提示：{info.prompt}</div>
          <div>订单号：{info.orderNumber}</div>
          <div>篮子号：{info.basketId}</div>
          <div>当前订单是否分拣完成：<Tag color={info.isFull ? 'rgb(253, 121, 1)' : ''}>{info.isFull ? '已完成' : '未完成'}</Tag></div>
          {info.list?.map((item: any, index: number) => {
            return <div key={item.id}>篮子编号：{item.id}，订单编号：{item.orderNumber}，总数: {item.total}，当前：{item.current}，操作时间：{item.updateTime} {item.id === info.basketId && info.isFull ?
              <Popconfirm
                title="确认发货？"
                okText="确定"
                cancelText="取消"
                placement="left"
                onConfirm={() => send(item)}
              ><Button className='mr-[10px]' type="primary">发货</Button></Popconfirm> : ''}{item.id === info.basketId && info.isFull ? <Popconfirm
                title="确认清空篮子？"
                okText="确定"
                cancelText="取消"
                placement="left"
                onConfirm={() => clearBasket(item, index)}
              ><Button type="primary" ghost>清空篮子</Button></Popconfirm> : ''}</div>;
          })}
        </div>

      </Card> : ''}
    </Space>
  );
}

// function CommonModal({ title, show, formValue, onOk, onCancel }: any) {
//   const [form] = Form.useForm();
//   useEffect(() => {
//     form.setFieldsValue({ ...formValue, finalPrice: toYuan(formValue.finalPrice) });
//   }, [formValue, form]);

//   const handleOk = () => {
//     const params = { ...formValue, ...form.getFieldsValue() };
//     params.finalPrice = toFen(params.finalPrice);
//     onOk(params);
//   };
//   return (
//     <Modal
//       title={title}
//       open={show}
//       onOk={() => handleOk()}
//       onCancel={onCancel}
//     >
//       <Form
//         initialValues={formValue}
//         form={form}
//         labelCol={{ span: 4 }}
//         wrapperCol={{ span: 18 }}
//         layout="horizontal"
//       >
//         <Form.Item<any> label="价格" name="finalPrice" required>
//           <InputNumber suffix="元" />
//         </Form.Item>
//       </Form>
//     </Modal>
//   );
// }
